package com.sgb.kjwl.view.ui.fragment.enterprise;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ProfessionalteamFragment2Binding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.Bean;
import com.sgb.kjwl.model.entity.enterprise.ProfessionalModel;
import com.sgb.kjwl.model.entity.enterprise.TeamChangeEntity;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.pop.TeamForEnterpisePopWindow;
import com.sgb.kjwl.utils.ActivityJump;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.swgk.core.util.UiUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.event.SearchEvent;
import com.sgb.kjwl.view.ui.activity.enterprise.ProfessionalTeamDetailActivity;
import com.sgb.kjwl.view.ui.adapter.enterprise.EpTeamAdapter;
import com.sgb.kjwl.view.ui.adapter.enterprise.NeedSelectAdapter;
import com.sgb.kjwl.view.widget.PickTwoLevelCityPopWindow2;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ScreenTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.xrecyclerview.XRecyclerView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import androidx.annotation.Nullable;
import androidx.core.util.Pair;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import static com.swgk.core.event.EventConstant.EVENT_PROFESSIONA_TEAM_FRG_JUMP;

/**
 * 作者:张磊
 * 日期:2020/12/24 0024
 * 说明:专业团队
 */
public class ProfessionalTeamFragment2 extends AppLazyFragment {
    @Inject
    ProfessionalModel mModel;

    private ProfessionalteamFragment2Binding mBinding;

    private NeedSelectAdapter mNeedSelectAdapter;


    private PickTwoLevelCityPopWindow2 mCityPopWindow;//选择地址
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> mCityDatas;
    private EpTeamAdapter mTeamAdapter;
    private String mProvinceNo,mProvinceNo2;
    private String mCityNo,mCityNo2;
    private Map<String, Object> mMap = new HashMap<>();
    private String mCategory;
    private ScreenTextView mScreenTextView;
    private List<Bean> mDatas1;
//    private List<Bean> mDatas2;
    private TeamForEnterpisePopWindow mNeedPopWindow;
//    private TeamForEnterpisePopWindow mNeedPopWindow2;
private ThreeLevelAreaWindow mAddressPop;

    private int position1 = 0;
    private boolean ChoiceProvinceOne = true;

    public static ProfessionalTeamFragment2 newInstance(String code) {
        ProfessionalTeamFragment2 fragment = new ProfessionalTeamFragment2();
        Bundle bundle = new Bundle();
        bundle.putString("code", code);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.professionalteam_fragment2, container, false);
        return mBinding.getRoot();
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initListener();
    }

    private void initListener() {
        mCityPopWindow.setOnDismissListener(() -> {

            mScreenTextView.contentSelectRed(ChoiceProvinceOne?!TextUtils.isEmpty(mProvinceNo)&&!mProvinceNo.contains("全国"):!TextUtils.isEmpty(mProvinceNo2)&&!mProvinceNo2.contains("全国"), false);
        });

        mNeedPopWindow.setOnDismissListener(()->{
            mScreenTextView.contentSelectRed(position1!=0, false);
        });
//        mNeedPopWindow2.setOnDismissListener(()->{
//            mScreenTextView.contentSelectRed(position2!=0,false );
//        });
        // 立即咨询
        mTeamAdapter.OnCallPhone((num, name) -> {
            if (DialogHelper.checkLogin()) {
                DialogHelper.showDialog(getActivity(), "确认呼叫", name + ":" + num, "确定", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        ActivityJump.jumpToPhone(getActivity(), num);
                    }
                });
            } else {
                DialogHelper.showLoginDialogNew(getContext(), EVENT_PROFESSIONA_TEAM_FRG_JUMP, "温馨提示", "登录后可拨打电话,去登录", "登录");
            }
        });
        // 点击item
        mTeamAdapter.setOnItemClick(new AdapterOnItemClick<TeamChangeEntity>() {
            @Override
            public void onItemClick(TeamChangeEntity teamChangeEntity, int position) {
                ActivityJump.jumpToActivity(getActivity(), ProfessionalTeamDetailActivity.class, Pair.create("id", teamChangeEntity.getId()));
            }
        });
        mBinding.displayView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mModel.getTeamQueryList(mMap, true);
            }

            @Override
            public void onLoadMore() {
                mModel.getTeamQueryList(mMap, false);
            }
        });

        // 城市弹框点击确定回调
        mCityPopWindow.setOnResultClick((key1, key2, key3) -> {
            if(ChoiceProvinceOne) {
                mProvinceNo = (String) key1;
                mCityNo = (String) key2;
                mMap.put("cityNo", mCityNo);
                mMap.put("provinceNo", mProvinceNo);
                mModel.getTeamQueryList(mMap, true);
//                mScreenTextView.contentSelectRed(!TextUtils.isEmpty(mProvinceNo), false);
            }else{
                mProvinceNo2 = (String) key1;
                mCityNo2 = (String) key2;
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setBgView(mBinding.grayLayout);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                if(ChoiceProvinceOne) {
                    mProvinceNo = (String) entity.getProvinceNo();
                    mCityNo = (String) entity.getCityNo();
                    mMap.put("cityNo", mCityNo);
                    mMap.put("provinceNo", mProvinceNo);
                    mModel.getTeamQueryList(mMap, true);
//                mScreenTextView.contentSelectRed(!TextUtils.isEmpty(mProvinceNo), false);
                }else{
                    mProvinceNo2 = (String) entity.getProvinceNo();
                    mCityNo2 = (String) entity.getCityNo();
                }
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mScreenTextView.contentSelectRed(ChoiceProvinceOne?!TextUtils.isEmpty(mProvinceNo)&&!mProvinceNo.contains("全国"):!TextUtils.isEmpty(mProvinceNo2)&&!mProvinceNo2.contains("全国"), false);
        });
        mNeedSelectAdapter.setOnItemClick(new AdapterOnItemClick<String>() {
            @Override
            public void onItemClick(String s, int position) {
                mScreenTextView = (ScreenTextView) mBinding.rvSelect.getChildAt(position);
                mScreenTextView.contentSelectRed(false, true);
                switch (position) {
                    case 0:
                        ChoiceProvinceOne = true;
//                    mProvinceNo = "";
                        if (mCityDatas == null) {
                            mModel.getServiceCity();
                        } else {
                            mAddressPop.showPopwindow0(mBinding.rvSelect);
//                        mCityPopWindow.setData(mCityDatas, false);
//                        mCityPopWindow.showPopwindow(mBinding.rvSelect, 0, 0);
                        }
                        break;
                    case 1:


                        if (!mNeedPopWindow.isShowing()) {
                            mNeedPopWindow.showPopwindow(mBinding.rvSelect, 0, 0);
                        }
                        break;
                    case 2://服务范围

                        ChoiceProvinceOne = false;
                        if (mCityDatas == null) {
                            mModel.getServiceCity();
                        } else {
                            mAddressPop.showPopwindow0(mBinding.rvSelect);
//                        mCityPopWindow.setData(mCityDatas, false);
//                        mCityPopWindow.showPopwindow(mBinding.rvSelect, 0, 0);
                        }

                        break;
                    case 3:

//                    if (!mNeedPopWindow2.isShowing()) {
//                        mNeedPopWindow2.showPopwindow(mBinding.rvSelect, 0, 0);
//                    }
                        break;
                }

            }
        });

        mNeedPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                position1 = (int)key2;

                switch (position1){
                    case 0:

                        mMap.remove("minScale");
                        mMap.remove("maxScale");
                        break;
                    case 1:
                        mMap.remove("minScale");
                        mMap.put("maxScale",10);
                        break;
                    case 2:
                        mMap.put("minScale",10);
                        mMap.put("maxScale",50);
                        break;
                    case 3:
                        mMap.put("minScale",50);
                        mMap.put("maxScale",100);
                        break;
                    case 4:
                        mMap.put("minScale",100);
                        mMap.put("maxScale",500);
                        break;

                    case 5:
                        mMap.put("minScale",500);
                        mMap.remove("maxScale");
                        break;
                }

                mModel.getTeamQueryList(mMap, true);

            }
        });

        mNeedPopWindow.setBgView(mBinding.grayLayout);
//        mNeedPopWindow2.setOnResultClick(new BasePopWindow.OnResultClick() {
//            @Override
//            public void result(Object key1, Object key2, Object key3) {
//                position2 = (int)key2;
//            }
//        });
    }

    private void initData() {
        List<String> beans = new ArrayList<>();
        beans.add("经营地址");
        beans.add("团队人数");
//        beans.add("服务范围");// todo 产品沟通暂时去掉服务范围
//        beans.add("是否自营");

        mDatas1 = new ArrayList<>();
        mDatas1.add(new Bean("不限"));
        mDatas1.add(new Bean("10人以下"));
        mDatas1.add(new Bean("10-50人"));
        mDatas1.add(new Bean("50-100人"));
        mDatas1.add(new Bean("100-500人"));
        mDatas1.add(new Bean("500人以上"));


//        mDatas2 = new ArrayList<>();
//        mDatas2.add(new Bean("不限"));
//        mDatas2.add(new Bean("自营"));
//        mDatas2.add(new Bean("非自营"));
        mNeedPopWindow.setData(mDatas1);
//        mNeedPopWindow2.setData(mDatas2);
        mNeedSelectAdapter.setDatas(beans);
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
        Bundle arguments = getArguments();
        mCategory = arguments.getString("code");
    }

    @Override
    public void initView() {

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(RecyclerView.HORIZONTAL);
        mBinding.rvSelect.setLayoutManager(manager);
        mNeedSelectAdapter = new NeedSelectAdapter(getContext(), null);
        mBinding.rvSelect.setAdapter(mNeedSelectAdapter);
        mCityPopWindow = new PickTwoLevelCityPopWindow2(getActivity());
        mNeedPopWindow = new TeamForEnterpisePopWindow(getActivity());
//        mNeedPopWindow2 = new TeamForEnterpisePopWindow(getActivity());
        mTeamAdapter = new EpTeamAdapter(getActivity(), null);
        mBinding.displayView.setLayoutManager(new LinearLayoutManager(UiUtil.getContext()));
        mBinding.displayView.setLoadingMoreEnabled(true);
        mBinding.displayView.setAdapter(mTeamAdapter);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @Override
    protected void onLazyLoad() {
        mMap.put("category", mCategory);
        mModel.getTeamQueryList(mMap, true);
    }

    // 获取所有城市并弹框
    public void getCityList(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> cityDatas) {
        mCityDatas = cityDatas;
        mAddressPop.setData(cityDatas, true);
        mAddressPop.showPopwindow0(mBinding.rvSelect);
//        mCityPopWindow.setData(cityDatas, false);
//        mCityPopWindow.showPopwindow(mBinding.rvSelect, 0, 0);
    }

    // 获取列表数据
    public void showList(List<TeamChangeEntity> data, boolean isRefresh) {
        mBinding.displayView.refreshComplete();
        if (isRefresh) {
            mBinding.displayView.setVisibility(data.size() != 0 ? View.VISIBLE : View.GONE);
            mBinding.errorView.setVisibility(data.size() != 0 ? View.GONE : View.VISIBLE);
//            ((TextView)mBinding.errorView.findViewById(R.id.no_data_tv)).setText("空空如也");
//            mBinding.errorView.findViewById(R.id.no_data_count).setVisibility(data.size() != 0 ? View.GONE : View.VISIBLE);
            mTeamAdapter.setDatas(data);
            mBinding.displayView.setLoadingMoreEnabled(true);
        } else {
            if (data.size() != 0) {
                mBinding.displayView.loadMoreComplete();
                mTeamAdapter.addDatas(data);
            } else {
                mBinding.displayView.setNoMore(true);
            }
        }
        mTeamAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(LoginEvent event) {
        if (event.getMessageTag() == EVENT_PROFESSIONA_TEAM_FRG_JUMP) {
            mModel.getTeamQueryList(mMap, true);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(SearchEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_SERVICE_SEARCH) {
            String searchParam = (String) event.getMessageData();
            Bundle arguments = getArguments();
            mCategory = arguments.getString("code");
            mMap.put("category", mCategory);
            mMap.put("searchParam",searchParam);
            mModel.getTeamQueryList(mMap, true);
        }
    }
}
